import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import { gql, useMutation, useQuery } from '@apollo/client';
import { Link } from 'react-router-dom';
import { CheckmarkFilled16 as ChoosedIcon } from '@carbon/icons-react';
import Button from '@kuiper-components/button';
import Dialog from '@kuiper-components/dialog';
import s from './NotificationDetail.module.css';

const QUERY_GQL = gql`
	{
		profile {
			_id
		}
	}
`;
const REPLY_NOTIFICATION = gql`
	mutation($id: MongoID!, $action: String!) {
		replyNotification(id: $id, action: $action) {
			_id
		}
	}
`;

export default function NotificationDetail({
	className,
	notification: { _id, title, message, category, action, choosedActionMap },
}) {
	const [visible, setVisible] = React.useState(false);

	const { data } = useQuery(QUERY_GQL, { fetchPolicy: 'cache-only' });
	const uid = data?.profile?._id;

	const [reply] = useMutation(REPLY_NOTIFICATION);
	const handleReply = ({ id, action }) => {
		reply({
			variables: {
				id,
				action,
			},
		});
	};

	return (
		<>
			<Button
				link
				className={cn(className, s.notificationDetail)}
				onClick={() => setVisible(true)}
			>
				查看
			</Button>
			<Dialog
				wrapClassName={s.dialog}
				visible={visible}
				onClose={() => setVisible(false)}
			>
				<b>
					[{category}] {title}
				</b>
				<div className={s.message}>{message}</div>
				<div
					className={cn(s.actions, {
						[s.disabled]: choosedActionMap[uid],
					})}
				>
					{Object.values(action).map(({ id, label, href }) =>
						href ? (
							<Link
								key={id}
								className={cn(s.action, {
									// prettier-ignore
									[s.choosed]: choosedActionMap[uid] === id,
								})}
								to={href}
							>
								<Button>
									{choosedActionMap[uid] === id && <ChoosedIcon />}
									{label}
								</Button>
							</Link>
						) : (
							<Button
								key={id}
								className={cn(s.action, {
									// prettier-ignore
									[s.choosed]: choosedActionMap[uid] === id,
								})}
								onClick={() =>
									handleReply({
										id: _id,
										action: id,
									})
								}
							>
								{choosedActionMap[uid] === id && <ChoosedIcon />}
								{label}
							</Button>
						)
					)}
				</div>
			</Dialog>
		</>
	);
}

NotificationDetail.propTypes = {
	className: PropTypes.string,
	notification: PropTypes.shape({
		_id: PropTypes.string.isRequired,
		title: PropTypes.string.isRequired,
		category: PropTypes.string.isRequired,
		message: PropTypes.string,
		choosedActionMap: PropTypes.object,
		action: PropTypes.object.isRequired,
	}),
};

NotificationDetail.defaultProps = {
	className: s.notificationDetail,
};
